package de.hszigr.inf.webapp;

import org.apache.click.control.Form;
import org.apache.click.control.HiddenField;
import org.apache.click.control.PasswordField;
import org.apache.click.control.Submit;
import org.apache.click.control.TextField;
import org.apache.click.extras.control.PageSubmit;
import org.apache.click.util.Bindable;

import de.hszigr.inf.model.User;
import de.hszigr.inf.usermanagement.UserManager;
import de.hszigr.inf.webapp.admin.HomeAdmin;
import de.hszigr.inf.webapp.common.BorderTemplate;
import de.hszigr.inf.webapp.teacher.HomeTeacher;

public class Login extends BorderTemplate {
	
    @Bindable protected Form form = new Form();
    @Bindable protected HiddenField redirectField = new HiddenField("redirect", String.class);

    private TextField usernameField = new TextField(getMessage("login.username"), true);
    private PasswordField passwordField = new PasswordField(getMessage("login.password"), true);
	
    private UserManager userManager = new UserManager();
	
	public Login(){
		title = getMessage("login.formtitle");
		setRole("other");
        usernameField.setMaxLength(20);
        usernameField.setFocus(true);
        form.add(usernameField);

        passwordField.setMaxLength(20);
        form.add(passwordField);

        form.add(new Submit("ok", getMessage("ok"), this, "onOkClicked"));
        form.add(new PageSubmit(getMessage("cancel"), HomeCMS.class));

        form.add(redirectField);
	}
	
	 public boolean onOkClicked() {
	        if (form.isValid()) {
	        	
	        	User u = userManager.isValidUser(usernameField.getValue(), passwordField.getValue());
	        	if(u != null){
	        		if(u.getRole().equals("admin")){
	        			getContext().setSessionAttribute("currentUser", u);
	        			setRedirect(HomeAdmin.class);
	        			
	        		}
	        		if(u.getRole().equals("teacher")){
	        			getContext().setSessionAttribute("currentUser", u);
	        			setRedirect(HomeTeacher.class);
	        		}
	        	}
	        	else{
	        		System.out.println("Login fehlgeschlagen");
	        		form.setError(getMessage("login.authentication-error"));
	        	}
	        	
	        }
	        
	        return true;
	 }
	        
		@Override
		public void onGet() {

		}
}